using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SqlCeViewer.Base;
using System.Reflection;
using CustomControl.DynaProgressBar;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars;
using SqlCeViewer.CommonMethod;
using SqlCeViewer.Utility;
using Microsoft.Practices.EnterpriseLibrary.Data.SqlCe;
using XLCS.Common;
using CustomControl.NewXLAGControl;
using SqlCeViewer.UI;
using System.Data.Common;

namespace SqlCeViewer.MainForm
{
    public partial class Main : BaseSubForm, IWindowIDE
    {
        private readonly string AppendUINamespace = "SqlCeViewer.FileFoderUI";

        private readonly string ModulsNameSpace = "SqlCeViewer.Moduls";

        private readonly string DynamicalLoadTypeError = "Invalid type when loading";

        public IDbEnginer X_MainEnginer
        {
            get
            {
                return GlobalInfo.MainEngineer;
            }
        }

        //ObservableCollection<String> CmdHistoryList = new ObservableCollection<String>();
        private List<string> _cmdHistoryList=new List<string>();

        public List<string> CmdHistoryList
        {
            get { return _cmdHistoryList; }
            set
            {
                _cmdHistoryList = value;
                CommandCurrency = _cmdHistoryList.Count;
            }
        }

        private int CommandCurrency = 0;

        public Main()
        {
            InitializeComponent();

            this.IsMdiContainer = true;

            LoadGeneralModules();
            LoadModules();
            
            Load += new EventHandler(Main_Load);
            Shown += new EventHandler(Main_Shown);
            FormClosing += new FormClosingEventHandler(Main_FormClosing);
            MakeMainMenu();
            txtMainCmd.KeyDown += new KeyEventHandler(txtMainCmd_KeyDown);

            ContextMenu xMenu = new ContextMenu();
            mainTreeView.ContextMenu = xMenu;

            mainTreeView.ContextMenu.Popup += new EventHandler(ContextMenu_Popup);

            this.ribbonControl1.Minimized = true;
        }

        PageSwitchProgressBar dp;

        /// <summary>
        /// Start Processing bar 
        /// </summary>
        private void StartProcessingBar()
        {
            if (Properties.Settings.Default.IsUseOldStyleProcessBar)
            {

                dp = PageSwitchProgressBar.X_BeginLoadingDialog();

                dp.SetColorStyle(PageSwitchProgressBar.ColorStyle.YellowStyle);
            }
            else
            {
                //this.progressBar1.Visibility = Visibility.Visible;
                //this.progressBar1.IsIndeterminate = true;
            }
        }

        /// <summary>
        /// Stop Processing bar shhowing
        /// </summary>
        private void StopProcessingBar()
        {
            if (Properties.Settings.Default.IsUseOldStyleProcessBar)
            {
                dp.X_EndLoadingDialog();
            }
            else
            {
                //this.progressBar1.Visibility = Visibility.Hidden;
                //this.progressBar1.IsIndeterminate = false;
            }
        }

        /// <summary>
        /// Get Current Selected TreeItem Value
        /// </summary>
        /// <returns></returns>
        private TreeItemArgs GetArgsFromSelectedItem()
        {
            TreeItemArgs result = null;

            TreeNode item = mainTreeView.SelectedNode as TreeNode;
            if (item != null)
            {
                result = item.Tag as TreeItemArgs;
            }
            return result;
        }

        /// <summary>
        /// Get the selected Item's parent itme value
        /// </summary>
        /// <returns></returns>
        private TreeItemArgs GetParentItemArgs()
        {
            TreeItemArgs result = null;

            TreeNode item = mainTreeView.SelectedNode as TreeNode;
            TreeNode parentItem = item.Parent as TreeNode;

            if (parentItem != null)
            {
                result = parentItem.Tag as TreeItemArgs;
            }
            return result;
        }

        /// <summary>
        /// Get Top nodes args
        /// </summary>
        /// <returns></returns>
        private TreeItemArgs GetTopNodeArgs()
        {
            TreeItemArgs result = null;

            TreeNode item = mainTreeView.SelectedNode as TreeNode;
            TreeNode parentItem = item.Parent as TreeNode;
            TreeNode topItem = parentItem.Parent as TreeNode;

            if (topItem != null)
            {
                result = topItem.Tag as TreeItemArgs;
            }
            return result;
        }



        void ContextMenu_Popup(object sender, EventArgs e)
        {
            ContextMenu menu = (ContextMenu)sender;

            //If db has no tables 
            if (this.mainTreeView.Nodes.Count < 1)
            {
                MakeContextmenu_WhenEmptyContent(menu);
                return;
            }

            //Determine the ContextMenu Content
            TreeItemArgs args = GetArgsFromSelectedItem();
            if (args != null)
            {
                switch (args.ItemType)
                {
                    case TreeItemType.Table:
                        MakeContextmenu_ForTable(menu);
                        break;
                    case TreeItemType.Column:
                        MakeContextmenu_ForColumn(menu);
                        break;
                    case TreeItemType.ColumnParentNode:
                        MakeContextmenu_ForAllColumn(menu);
                        break;
                    case TreeItemType.IndexParentNode:

                        break;
                    case TreeItemType.Index:
                        MakeContextmenu_ForAllIndex(menu);
                        break;
                    default:
                        break;
                }
            }
            //if tree has content ,but user don't select any , then allow use control system level sql action
            else
            {
                 MakeContextmenu_WhenNoSelection(menu);
            }
        }

        private void MakeContextmenu_ForAllIndex( ContextMenu ctMenu )
        {
            ctMenu.MenuItems.Clear();
            MenuItem itemDropIndex = new MenuItem();
            itemDropIndex.Text = "Drop Index";
            itemDropIndex.Click += delegate { itemDropIndex_Click(); };
            ctMenu.MenuItems.Add(itemDropIndex);
        }

        private void MakeContextmenu_ForAllColumn(ContextMenu ctMenu)
        {
            ctMenu.MenuItems.Clear();
            MenuItem itemInsertColumn = new MenuItem();
            itemInsertColumn.Text = "Insert Column";
            itemInsertColumn.Click += delegate { itemInsertColumn_Click(false); };
            ctMenu.MenuItems.Add(itemInsertColumn);
        }

        /// <summary>
        /// Current use MakeContextmenu_WhenEmptyContent() ContextMenu
        /// But in the future, if necessary , refactor it
        /// </summary>
        /// <returns></returns>
        private void MakeContextmenu_WhenNoSelection(ContextMenu menu)
        {
            MakeContextmenu_WhenEmptyContent(menu);
        }



        /// <summary>
        /// When db has no tables 
        /// </summary>
        private void MakeContextmenu_WhenEmptyContent(ContextMenu menu)
        {
            menu.MenuItems.Clear();

            MenuItem itemCreateTable = new MenuItem();
            itemCreateTable.Text = "Create Table";
            itemCreateTable.Click += delegate { itemCreateTable_Click(); };
            menu.MenuItems.Add(itemCreateTable);

        }


        /// <summary>
        /// Content for Column
        /// </summary>
        private void MakeContextmenu_ForColumn(ContextMenu ctMenu)
        {
            ctMenu.MenuItems.Clear();
            MenuItem itemDropColumn = new MenuItem();
            itemDropColumn.Text = "Drop Column";
            itemDropColumn.Click += delegate { itemDropColumn_Click(); };
            ctMenu.MenuItems.Add(itemDropColumn);

            MenuItem itemRenameColumn = new MenuItem();
            itemRenameColumn.Text = "Rename Column";
            itemRenameColumn.Click += delegate { itemRenameColumn_Click(); };
            ctMenu.MenuItems.Add(itemRenameColumn);

            MenuItem itemModidyTypeColumn = new MenuItem();
            itemModidyTypeColumn.Text = "Modify Column";
            itemModidyTypeColumn.Click += delegate { itemModifyTypeColumn_Click(); };
            ctMenu.MenuItems.Add(itemModidyTypeColumn);

            MenuItem itemInsertColumn = new MenuItem();
            itemInsertColumn.Text = "Insert Column";
            itemInsertColumn.Click += delegate { itemInsertColumn_Click(true); };
            ctMenu.MenuItems.Add(itemInsertColumn);

            ctMenu.MenuItems.Add("-");

            MenuItem itemCreateIndex = new MenuItem();
            itemCreateIndex.Text = "Create Index";
            itemCreateIndex.Click += delegate { itemCreateIndex_Click(); };
            ctMenu.MenuItems.Add(itemCreateIndex);

            ctMenu.MenuItems.Add("-");
            MenuItem itemCopyColumnName = new MenuItem();
            itemCopyColumnName.Text = "Copy Column Name";
            itemCopyColumnName.Click += delegate { itemCopyColumnName_Click(); };
            ctMenu.MenuItems.Add(itemCopyColumnName);

        }

        private void itemCopyColumnName_Click()
        {
            Clipboard.SetText(GetArgsFromSelectedItem().ColumnName);
        }

        /// <summary>
        /// Insert a column
        /// </summary>
        /// <param name="IsFromTableNode">Indicate this event is raised from Which kind of TreeItemType</param>
        /// 
        private void itemInsertColumn_Click(bool IsFromTableNode)
        {
            string tableName = string.Empty;
            if (IsFromTableNode)
            {
                tableName = GetArgsFromSelectedItem().TableName;
            }
            else
            {
                tableName = GetParentItemArgs().TableName;
            }

            txtMainCmd.Text = String.Format("ALTER TABLE [{0}] ADD COLUMN [ColumnName] [ColumnType]", tableName);

            txtMainCmd.Select(txtMainCmd.Text.IndexOf('['), 10);
        }

        /// <summary>
        /// Modify Column type
        /// </summary>
        private void itemModifyTypeColumn_Click()
        {
            string tableName = GetTopNodeArgs().TableName;

            txtMainCmd.Text = String.Format("ALTER TABLE [{0}]  ALTER COLUMN {1} [NewType] ", tableName, GetArgsFromSelectedItem().ColumnName);
        }



        /// <summary>
        /// Delete Column
        /// </summary>
        private void itemDropColumn_Click()
        {

            if (MessageBox.Show("Do you confirm this action", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                string tableName = GetTopNodeArgs().TableName;

                txtMainCmd.Text = String.Format("ALTER TABLE [{0}]  Drop COLUMN {1} ", tableName, GetArgsFromSelectedItem().ColumnName);

                butExecuteCmd_Click(null, null);

                txtMainCmd.Text = string.Empty;
            }
        }


        private void itemRenameColumn_Click()
        {


            string tableName = GetTopNodeArgs().TableName;

            string newColumnName = string.Empty;

        ReDo:
            using (PopupForm p = new PopupForm())
            {
                p.X_NotifyStr = "Column name";
                if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    newColumnName = p.X_Result;
                }
                else
                {
                    return;
                }
            }

            if (newColumnName.Length > 200)
            {
                MessageBox.Show(String.Format("Sql Ce Column name length must large than {0} ", 200));

                goto ReDo;
            }

            txtMainCmd.Text = String.Format("ALTER TABLE [{0}]  RENAME COLUMN {1} To {2}", tableName, GetArgsFromSelectedItem().ColumnName, newColumnName);

            butExecuteCmd_Click(null, null);

            txtMainCmd.Text = string.Empty;



        }


        /// <summary>
        /// Content for table based
        /// </summary>
        private void  MakeContextmenu_ForTable(ContextMenu ctMenu)
        {
            ctMenu.MenuItems.Clear();
            MenuItem itemSelectAll = new MenuItem();
            itemSelectAll.Text = "Select all";
            itemSelectAll.Click += delegate { itemSelectAll_Click(); };
            ctMenu.MenuItems.Add(itemSelectAll);

            ctMenu.MenuItems.Add("-");

            MenuItem itemSelect = new MenuItem();
            itemSelect.Text = "Select ...";
            itemSelect.Click += delegate { itemSelect_Click(); };
            ctMenu.MenuItems.Add(itemSelect);

            MenuItem itemInsert = new MenuItem();
            itemInsert.Text = "Insert ...";
            itemInsert.Click += delegate { itemInsert_Click(); };
            ctMenu.MenuItems.Add(itemInsert);

            MenuItem itemUpdate = new MenuItem();
            itemUpdate.Text = "Update ...";
            itemUpdate.Click += delegate { itemUpdate_Click(); };
            ctMenu.MenuItems.Add(itemUpdate);

            MenuItem itemDelete = new MenuItem();
            itemDelete.Text = "Delete ...";
            itemDelete.Click += delegate { itemDelete_Click(); };
            ctMenu.MenuItems.Add(itemDelete);


            ctMenu.MenuItems.Add("-");

            MenuItem itemInsertDataRow = new MenuItem();
            itemInsertDataRow.Text = "Insert a row";
            itemInsertDataRow.Click += delegate { itemInsertDataRow_Click(); };
            ctMenu.MenuItems.Add(itemInsertDataRow);

            ctMenu.MenuItems.Add("-");

            MenuItem itemCreateTable = new MenuItem();
            itemCreateTable.Text = "Create table";
            itemCreateTable.Click += delegate { itemCreateTable_Click(); };
            ctMenu.MenuItems.Add(itemCreateTable);

            MenuItem itemRenameTable = new MenuItem();
            itemRenameTable.Text = "Rename table...";
            itemRenameTable.Click += delegate { itemRenameTable_Click(); };
            ctMenu.MenuItems.Add(itemRenameTable);

            MenuItem itemDeleteTable = new MenuItem();
            itemDeleteTable.Text = "Drop table";
            itemDeleteTable.Click += delegate { itemDeleteTable_Click(); };
            ctMenu.MenuItems.Add(itemDeleteTable);

            MenuItem itemModifySchema = new MenuItem();
            itemModifySchema.Text = "Modify Table Schema";
            itemModifySchema.Click += delegate { itemModifySchema_Click(); };
            ctMenu.MenuItems.Add(itemModifySchema);

            ctMenu.MenuItems.Add("-");

            MenuItem itemGetColumnsInfo = new MenuItem();
            itemGetColumnsInfo.Text = "Get All columns info";
            itemGetColumnsInfo.Click += delegate { itemGetColumnsInfo_Click(); };
            ctMenu.MenuItems.Add(itemGetColumnsInfo);

            MenuItem itemGetIndexesInfo = new MenuItem();
            itemGetIndexesInfo.Text = "Get All Indexes info";
            itemGetIndexesInfo.Click += delegate { itemGetIndexesInfo_Click(); };
            ctMenu.MenuItems.Add(itemGetIndexesInfo);

            ctMenu.MenuItems.Add("-");

            MenuItem itemProviderInfo = new MenuItem();
            itemProviderInfo.Text = "Get supported type";
            itemProviderInfo.Click += delegate { itemProviderInfo_Click(); };
            ctMenu.MenuItems.Add(itemProviderInfo);

        }

        private void itemSelect_Click()
        {
            txtMainCmd.Text = String.Format("SELECT * FROM [{0}]", GetArgsFromSelectedItem().TableName);

        }

        private void itemInsert_Click()
        {
            txtMainCmd.Text = String.Format("INSERT INTO [{0}] (COLUMN_NAME) VALUES (COLUMN_VALUE)", GetArgsFromSelectedItem().TableName);

        }

        private void itemUpdate_Click()
        {

            txtMainCmd.Text = String.Format("UPDATE [{0}] SET (COLUMN_NAME) = (COLUMN_VALUE) ", GetArgsFromSelectedItem().TableName);

        }

        private void itemDelete_Click()
        {
            txtMainCmd.Text = String.Format("Delete from [{0}] WHERE (COLUMN_NAME) = (COLUMN_VALUE) ", GetArgsFromSelectedItem().TableName);
        }

        private void itemProviderInfo_Click()
        {
            FillUI(GlobalInfo.MainEngineer.GetProviderInfoFromTable(GetArgsFromSelectedItem().TableName));
        }



        private void itemGetIndexesInfo_Click()
        {
            FillUI(GlobalInfo.MainEngineer.GetIndexInfoFromTable(GetArgsFromSelectedItem().TableName));
        }

        private void itemGetColumnsInfo_Click()
        {
            FillUI(GlobalInfo.MainEngineer.GetColumnInfoFromTable(GetArgsFromSelectedItem().TableName));
        }

        /// <summary>
        /// 
        /// </summary>
        private void itemModifySchema_Click()
        {
            //CreateTableDetailWindow ct = new CreateTableDetailWindow(CreateTableDetailWindow.EnteringType.ModifySchema, GetArgsFromSelectedItem().TableName);

            //ct.Owner = this;

            //ct.ShowDialog();
        }

        private void itemDropIndex_Click()
        {

            if (MessageBox.Show("Do you confirm this action", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                txtMainCmd.Text = String.Format("DROP INDEX [{0}].[{1}]", GetTopNodeArgs().TableName, GetTopNodeArgs().IndexName);

                butExecuteCmd_Click(null, null);

                txtMainCmd.Text = string.Empty;
            }

        }

        private void itemCreateIndex_Click()
        {
            string newIndexName = string.Empty;
        ReDo:
            using (PopupForm p = new PopupForm())
            {
                p.X_NotifyStr = "Index name";
                if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    newIndexName = p.X_Result;
                }
                else
                {
                    return;
                }
            }

            if (newIndexName.Length > 20)
            {
                MessageBox.Show(String.Format("Index name length must large than {0} ", 20));

                goto ReDo;
            }

            txtMainCmd.Text = String.Format("CREATE UNIQUE INDEX {0} ON [{1}] ({2}) ", newIndexName, GetParentItemArgs().TableName, GetArgsFromSelectedItem().ColumnName);
            butExecuteCmd_Click(null, null);

            txtMainCmd.Text = string.Empty;


        }

        /// <summary>
        /// Insert a row data in current table
        /// </summary>
        private void itemInsertDataRow_Click()
        {

            string tableName = GetArgsFromSelectedItem().TableName;
            string args = string.Empty;

            DataSet dataRowCollections = GlobalInfo.MainEngineer.GetColumnInfoFromTable(tableName);
            args += "( ";
            foreach (DataRow item in dataRowCollections.Tables[0].Rows)
            {
                args += item["COLUMN_NAME"] + ",";
            }
            args = args.Substring(0, args.Length - 1);

            args += ") VALUES (";

            for (int i = 0; i < dataRowCollections.Tables[0].Rows.Count; i++)
            {
                switch (dataRowCollections.Tables[0].Rows[i]["DATA_TYPE"].ToString())
                {
                    case "int":
                        args += String.Format(" {0},", i.ToString());
                        break;

                    default:
                        args += String.Format(" '{0}',", i.ToString());
                        break;
                }


            }

            args = args.Substring(0, args.Length - 1);

            args += " )";

            txtMainCmd.Text = String.Format("INSERT INTO [{0}] {1}", tableName, args);
        }

        /// <summary>
        /// Delete Table
        /// </summary>
        private void itemDeleteTable_Click()
        {

            if (MessageBox.Show("Do you confirm this action", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                txtMainCmd.Text = String.Format("DROP TABLE [{0}] ", GetArgsFromSelectedItem().TableName);

                butExecuteCmd_Click(null, null);

                txtMainCmd.Text = string.Empty;
            }
        }

        /// <summary>
        /// Rename table
        /// </summary>
        void itemRenameTable_Click()
        {
            string newTableName = string.Empty;

        ReDo:
            using (PopupForm p = new PopupForm())
            {
                p.X_NotifyStr = "Table name";
                if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    newTableName = p.X_Result;
                }
                else
                {
                    return;
                }
            }

            if (newTableName.Length > GlobalInfo.MainEngineer.GetTableMaxLength)
            {
                MessageBox.Show(String.Format("Sql Ce table name length must large than {0} ", GlobalInfo.MainEngineer.GetTableMaxLength));

                goto ReDo;
            }

            txtMainCmd.Text = string.Format("ALTER TABLE [{0}] RENAME TO [{1}] ", GetArgsFromSelectedItem().TableName, newTableName);

            butExecuteCmd_Click(null, null);

            txtMainCmd.Text = string.Empty;

        }

        /// <summary>
        /// Select Cmd
        /// </summary>
        void itemSelectAll_Click()
        {
            txtMainCmd.Text = string.Format("Select * from [{0}]", GetArgsFromSelectedItem().TableName);

            butExecuteCmd_Click(null, null);

            txtMainCmd.Text = string.Empty;

        }

        /// <summary>
        /// Create table sql command
        /// </summary>
        private void itemCreateTable_Click()
        {
            SwitchCreateTable st = new SwitchCreateTable();
            st.ShowDialog();
            switch (st.CurCreateType)
            {
                case SwitchCreateTable.CreateType.NotSelected:
                    return;
                case SwitchCreateTable.CreateType.Simple:
                    goto ReDo;
                case SwitchCreateTable.CreateType.Normal:

                    CreateTableDetailWindow ct = new CreateTableDetailWindow(CreateTableDetailWindow.EnteringType.CreateTable);
                    ct.RaiseAddNewTable += delegate { RefreshCurrentDbStatus(); };
                    ct.ShowDialog();

                    return;
                default:
                    return;
            }



        ReDo:
            string tableName = string.Empty;
            using (PopupForm p = new PopupForm())
            {
                p.X_NotifyStr = "Table name";
                if (p.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    tableName = p.X_Result;
                }
                else
                {
                    return;
                }
            }

            if (tableName.Length > GlobalInfo.MainEngineer.GetTableMaxLength)
            {
                MessageBox.Show(String.Format("Table name length must large than {0} ", GlobalInfo.MainEngineer.GetTableMaxLength));

                goto ReDo;
            }

            txtMainCmd.Text = String.Format("Create table [{0}] (ID int , Comment nvarchar(255))", tableName);



        }


        private void MakeMainMenu()
        {
            ////Other menus
            //MenuItem subMenu_Version = new MenuItem();
            //subMenu_Version.Name = "versionMenu";
            //subMenu_Version.Text = (object)"Version";
            //subMenu_Version.Click += delegate { MessageBox.Show(Application.ProductVersion); };
            ////Exit menu
            //MenuItem subMenu_Exit = new MenuItem();
            //subMenu_Exit.Name = "exitMenu";
            //subMenu_Exit.Text = (object)"Exit";
            //subMenu_Exit.Click += delegate { this.Close(); };

            //menuFile.Items.Add(subMenu_Exit);
            //menuFile.Items.Add(subMenu_Version);

        }

        void txtMainCmd_KeyDown(object sender, KeyEventArgs e)
        {

            if ((e.KeyCode == Keys.B) && (e.Modifiers == Keys.Control))
            {
                BackCmd(null, null);
            }
            else if ((e.KeyCode == Keys.N) && (e.Modifiers == Keys.Control))
            {
                NextCmd(null, null);
            }

            if (String.IsNullOrEmpty(txtMainCmd.Text))
            {
                return;
            }

            if (e.KeyCode == Keys.Enter)
            {
                butExecuteCmd_Click(null, null);
            }

            else if ((e.KeyCode == Keys.J) && (e.Modifiers == Keys.Control))
            {
                DynaControls.GetDbTypeControl dj = new DynaControls.GetDbTypeControl();
                dj.Location = new System.Drawing.Point(200, 200);
                dj.AfterSelectedValue += new DynaControls.GetDbTypeControl.Del_AfterSelectedValue(AcceptValue);

                dj.ShowDialog();

                e.Handled = true;
            }

        }

        private void BackCmd(object sender, EventArgs e)
        {
            if (CommandCurrency - 1 >= 0)
            {
                CommandCurrency--;
                txtMainCmd.Text = CmdHistoryList[CommandCurrency];
            }
        }

        private void NextCmd(object sender, EventArgs e)
        {
            if (CommandCurrency + 1 < CmdHistoryList.Count)
            {
                CommandCurrency++;
                txtMainCmd.Text = CmdHistoryList[CommandCurrency];
            }
        }



        void AcceptValue(string result)
        {
            if (String.IsNullOrEmpty(txtMainCmd.SelectedText))
            {
                txtMainCmd.Text += "  " + result;
            }
            else
            {
                txtMainCmd.SelectedText = string.Empty;

                int start = txtMainCmd.SelectionStart;
                string prefix = txtMainCmd.Text.Substring(0, start);
                string appdenfix = txtMainCmd.Text.Substring(start, txtMainCmd.Text.Length - start);

                prefix += result;

                txtMainCmd.Text = prefix + appdenfix;
            }

            //this.Activate();
            //this.txtMainCmd.Focus();
        }


        private void ResetUI()
        {
            this.mainTreeView.Nodes.Clear();
            txtMainCmd.Text = String.Empty;
        }

        void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                ((SqlCeDatabase)GlobalInfo.MainEngineer.DbHandler).CloseSharedConnection();

                ResetUI();
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);
            }
        }

        void Main_Load(object sender, EventArgs e)
        {
            this.mainTreeView.Nodes.Clear();
            //Clear to Orginal Status

            foreach (string table in GlobalInfo.MainEngineer.TableList)
            {
                TreeNode item = new TreeNode();
                item.Text = table;
                TreeItemArgs args = new TreeItemArgs();
                args.ItemType = TreeItemType.Table;
                args.TableName = table;
                item.Tag = args;

                mainTreeView.Nodes.Add(item);
            }

            foreach (TreeNode selectedItem in mainTreeView.Nodes)
            {
                if (selectedItem != null)
                {
                    TreeItemArgs args = selectedItem.Tag as TreeItemArgs;
                    if (args != null)
                    {
                        if (args.ItemType == TreeItemType.Table)
                        {
                            ListColumnsInTable(selectedItem, args.TableName);
                        }
                    }
                }

            }
            mainTreeView.ExpandAll();
        }

        /// <summary>
        /// Display the column info of this table in the curretn TreeNode
        /// </summary>
        /// <param name="selectedItem"></param>
        /// <param name="p"></param>
        private void ListColumnsInTable(TreeNode selectedItem, string tableName)
        {

            TreeNode columnItem = new TreeNode();
            columnItem.Text = "Columns";
            TreeItemArgs args = new TreeItemArgs();
            args.ItemType = TreeItemType.ColumnParentNode;
            args.TableName = tableName;
            columnItem.Tag = args;
            selectedItem.Nodes.Add(columnItem);

            TreeNode indexItem = new TreeNode();
            indexItem.Text = "Indexes";
            TreeItemArgs args_Index = new TreeItemArgs();
            args_Index.ItemType = TreeItemType.IndexParentNode;
            args_Index.TableName = tableName;

            indexItem.Tag = args_Index;

            selectedItem.Nodes.Add(indexItem);

            DataSet dataRowCollections = GlobalInfo.MainEngineer.GetColumnInfoFromTable(tableName);
            foreach (DataRow row in dataRowCollections.Tables[0].Rows)
            {
                TreeNode item = new TreeNode();
                item.Text = String.Format("{0}  {1}  {2}", row["COLUMN_NAME"], row["DATA_TYPE"], row["CHARACTER_MAXIMUM_LENGTH"]);
                TreeItemArgs args_columns = new TreeItemArgs();
                args_columns.ItemType = TreeItemType.Column;
                args_columns.TableName = tableName;
                args_columns.ColumnName = row["COLUMN_NAME"].ToString();
                item.Tag = args_columns;

                columnItem.Nodes.Add(item);
            }

            DataSet indexCollections = GlobalInfo.MainEngineer.GetIndexInfoFromTable(tableName);

            foreach (DataRow row in indexCollections.Tables[0].Rows)
            {
                TreeNode item = new TreeNode();
                item.Text = String.Format("{0}  {1}  {2}", row["INDEX_NAME"], "", "");

                TreeItemArgs args_Indexs = new TreeItemArgs();
                args_Indexs.ItemType = TreeItemType.Index;
                args_Indexs.TableName = tableName;
                args_Indexs.IndexName = row["INDEX_NAME"].ToString();
                item.Tag = args_Indexs;

                indexItem.Nodes.Add(item);
            }


        }


        void Main_Shown(object sender, EventArgs e)
        {
            BringToFront();
            Activate();
        }

        /// <summary>
        /// Loca inner modules
        /// </summary>
        private void LoadModules()
        {
            try
            {
                Type[] subTypes = Assembly.GetExecutingAssembly().GetTypes();
                if (subTypes == null)
                {
                    MessageBox.Show(DynamicalLoadTypeError);
                    return;
                }
                string tempFileName = string.Empty;



                int i = 0;

                foreach (Type subType in subTypes)
                {
                    if ((subType.IsClass) && (subType.IsPublic) && (!subType.IsInterface) && (!subType.IsAbstract) && (subType.FullName.Contains(ModulsNameSpace)))
                    {
                        RibbonPageGroup tempRibbonGroup = new RibbonPageGroup();
                        
                        this.ribbonPage2.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] { tempRibbonGroup });

                        BarButtonItem tempButItem = new BarButtonItem();
                        tempButItem.Width = 40;
                        Form t = (Form)Activator.CreateInstance(subType);

                        tempButItem.Caption = t.Text;// "  " + subType.Name + "  ";
                        tempButItem.Name = subType.Name;
                        tempButItem.LargeImageIndex = i;
                        tempRibbonGroup.ItemLinks.Add(tempButItem);
                        tempButItem.ItemClick += delegate { tempButItem_ItemClick(tempButItem.Name, ModulsNameSpace); };
                        i++;
                    }
                }

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.InnerException.Message);

            }


        }


        private void LoadGeneralModules()
        {
            try
            {

                Type[] subTypes = Assembly.GetExecutingAssembly().GetTypes();
                if (subTypes == null)
                {
                    MessageBox.Show(DynamicalLoadTypeError);
                    return;
                }
                string tempFileName = string.Empty;

                int i = 5;

                foreach (Type subType in subTypes)
                {
                    if ((subType.IsClass) && (subType.IsPublic) && (!subType.IsInterface) && (!subType.IsAbstract) && (subType.FullName.Contains(AppendUINamespace)))
                    {
                        RibbonPageGroup tempRibbonGroup = new RibbonPageGroup();

                        this.ribbonPage1.Groups.AddRange(new DevExpress.XtraBars.Ribbon.RibbonPageGroup[] { tempRibbonGroup });

                        BarButtonItem tempOtherButItem = new BarButtonItem();
                        tempOtherButItem.Caption = "  " + subType.Name + "  ";
                        tempOtherButItem.Name = subType.Name;
                        tempOtherButItem.LargeImageIndex = i;
                        tempRibbonGroup.ItemLinks.Add(tempOtherButItem);
                        tempOtherButItem.ItemClick += delegate { tempButItem_ItemClick(tempOtherButItem.Name, AppendUINamespace); };
                        i++;
                    }
                }

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.InnerException.Message);

            }

        }

        void tempButItem_ItemClick(string name, string typeNamespace)
        {
            foreach (Form subForm in this.MdiChildren)
            {
                if (subForm.Name == name)
                {
                    subForm.BringToFront();
                    subForm.Activate();
                    return;
                }
            }

            PageSwitchProgressBar fp = PageSwitchProgressBar.X_BeginLoadingDialog();
            fp.SetColorStyle(PageSwitchProgressBar.ColorStyle.YellowStyle);
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("Invalid Action");
                return;
            }

            new Util().ShowDialogSubUtil(name, typeNamespace);

            fp.X_EndLoadingDialog();
        }

        #region IWindowIDE Members

        public Form MyHost
        {
            get
            {
                return this;

            }
        }

        #endregion

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            mainTreeView.ExpandAll();
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            mainTreeView.CollapseAll();
        }

        private void butExecuteCmd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtMainCmd.Text))
            {
                MessageBox.Show("Please input the query command first");
                return;
            }
            string cmdText = ParseCmd(txtMainCmd.Text);

            CmdHistoryList.Add(cmdText);

            DbCommand cmd = GlobalInfo.MainEngineer.DbHandler.GetSqlStringCommand(cmdText);
            switch (_curCmdType)
            {
                case CurCommandType.Query:

                    Do_SelectCmd(cmd);

                    break;
                case CurCommandType.Update:

                    Do_UpdateCmd(cmd);

                    break;
                case CurCommandType.Delete:

                    Do_DeleteCmd(cmd);

                    break;
                case CurCommandType.Insert:

                    Do_InsertCmd(cmd);

                    break;
                case CurCommandType.SystemAction:

                    Do_SysCmd(cmd);

                    break;
                case CurCommandType.CreateTable:

                    Do_CreateTableCmd(cmd);

                    break;
                case CurCommandType.Unknown:

                    ProcessException.DisplayErrors(new Exception("Not valid command"));

                    break;
                default:
                    Do_SelectCmd(cmd);
                    break;
            }

            txtMainCmd.Text = string.Empty;
        }


    }
}